#!/usr/bin/env python3
"""
测试完整的大视频分析流程
"""

import asyncio
from pathlib import Path
from app.services.large_video_analyzer import LargeVideoAnalyzer

async def test_complete_analysis():
    """测试完整的大视频分析流程"""
    
    video_path = Path("uploads/90e15f07-59de-4250-b611-f1cbc6940acc.mp4")
    
    if not video_path.exists():
        print(f"❌ 视频文件不存在: {video_path}")
        return
    
    print(f"🧪 测试完整的大视频分析流程")
    print(f"📹 视频文件: {video_path}")
    
    analyzer = LargeVideoAnalyzer()
    
    try:
        # 测试分析流程（不进行实际AI分析，只测试到拆分阶段）
        print(f"\n1️⃣ 开始大视频分析...")
        
        prompt = "请分析视频内容"
        
        # 由于AI服务不可用，我们只测试拆分部分
        # 直接调用拆分方法
        split_result = await analyzer.video_splitter.split_video_by_duration(
            video_path, 
            segment_duration=60,
            max_segments=50,
            min_segment_duration=10
        )
        
        print(f"   拆分结果:")
        print(f"     需要拆分: {split_result.get('need_split')}")
        print(f"     片段数量: {len(split_result.get('segments', []))}")
        
        if split_result.get('segments'):
            print(f"   前5个片段:")
            for i, segment in enumerate(split_result['segments'][:5]):
                print(f"     {i+1}. {segment['filename']} ({segment.get('duration', 0):.1f}s)")
            
            print(f"   后5个片段:")
            for i, segment in enumerate(split_result['segments'][-5:], len(split_result['segments'])-4):
                print(f"     {i}. {segment['filename']} ({segment.get('duration', 0):.1f}s)")
        
        # 检查所有片段文件是否存在
        print(f"\n2️⃣ 验证片段文件...")
        missing_files = 0
        total_size = 0
        
        for segment in split_result.get('segments', []):
            segment_path = Path(segment['path'])
            if segment_path.exists():
                total_size += segment_path.stat().st_size
            else:
                missing_files += 1
        
        print(f"   缺失文件数: {missing_files}")
        print(f"   总文件大小: {total_size / (1024*1024):.1f}MB")
        print(f"   平均片段大小: {total_size / len(split_result.get('segments', [1])) / (1024*1024):.1f}MB")
        
        if missing_files == 0:
            print(f"   ✅ 所有片段文件都存在")
        else:
            print(f"   ❌ 有 {missing_files} 个片段文件缺失")
        
        # 测试URL访问
        print(f"\n3️⃣ 测试片段URL...")
        if split_result.get('segments'):
            first_segment = split_result['segments'][0]
            print(f"   第一个片段URL: {first_segment['url']}")
            print(f"   文件路径: {first_segment['path']}")
            
            # 检查URL格式是否正确
            expected_pattern = "http://192.168.210.72:8000/videos/segments/"
            if first_segment['url'].startswith(expected_pattern):
                print(f"   ✅ URL格式正确")
            else:
                print(f"   ❌ URL格式错误")
        
        print(f"\n🎉 拆分测试完成！现在可以进行实际的大视频分析了。")
        
    except Exception as e:
        print(f"❌ 测试失败: {e}")
        import traceback
        traceback.print_exc()

if __name__ == "__main__":
    asyncio.run(test_complete_analysis())